package org.fjsei.yewu.job;

import org.fjsei.yewu.repository.Teacher;
import org.fjsei.yewu.service.JpaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.UUID;

/**压力测试 疲劳测试 用的
小强数据库似乎都要@Transactional(propagation = Propagation.REQUIRES_NEW)只能单独放入服务层某个数据库函数中，外部控制器层次接口函数再调用数据库处理函数。
 *
 * */
@Deprecated
@Component
@Order(Ordered.LOWEST_PRECEDENCE)
public class TeacherClient implements CommandLineRunner {
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    @Value("${sei.clientjob:false}")
    private boolean  isClientJob;
    //访问对方接口的,客户端模式
    private final RestTemplate restTemplate;
    final String  urlstr="http://localhost:8673/teacher";

    @Autowired
    private JpaService jpaService;
    //static int countJob=0;

    public TeacherClient(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }
    //下面Scheduled和这个run执行顺序没关系
    @Override
    public void run(String... args) throws InterruptedException {   //没啥用处！
        Thread.sleep(2*1000);
        logger.info("Clear all...");
        initClearAll();
    }
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void initClearAll() {
        //Assert.isTrue(TransactionSynchronizationManager.isActualTransactionActive(), "TX not active");
    }
    public void innerJobThreadWorker本地(int tid) {
        String age= UUID.randomUUID().toString().trim().replaceAll("-", "");
        Teacher teacher=Teacher.builder().modelType("herzhang").build();
        teacher=jpaService.addTeacher(teacher);
        logger.info("生成 {}", teacher.getModelType());
    }
    /**独立服务器，配和个客户端;
     * 通用restTemplate.exchange(); 列表对象获取
     RestTemplate client= restTemplateBuilder.build();
     String uri = base+"/orders?offset={offset }";
     Integer offset = 1;
     HttpEntity body = null;
     ParameterizedTypeReference<List<Order> typeRef = new ParameterizedTypeReference<List<Order>(){};
     ResponseEntity<List<Order> rs=client.exchange(uri, HttpMethod.GET, body, typeRef, offset);
     List<Order> order = rs.getBody() ;
     * */
    public void innerJobThreadWorker(int tid) {
        do {
            try {
                String age= UUID.randomUUID().toString().trim().replaceAll("-", "");
                Teacher teacher=Teacher.builder().modelType("herzhang").build();
                ResponseEntity<Object> responseEntity = restTemplate
                        .postForEntity(urlstr, teacher, Object.class);
                Object ress= responseEntity.getBody();
                String retid= ress.toString();
                logger.info("答{},{}", tid,retid);
            } catch ( Exception | Error  ex) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }while (true);
    }
    //10个测试作业独立线程，并发进行。
    //@Scheduled(cron = "0 0 2 * * ?")　　//每天凌晨两点执行 @Scheduled(cron = "0 0 */2 * * ?")每两个小时执行一次，cron只能固定时间
    //@Scheduled(cron = "0 0/1 * * * ?")//每一分钟执行一次 @Scheduled执行一次可能泄露一次一点内存。
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc0() {
        int countJob=1;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc1() {
        int countJob=2;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc2() {
        int countJob=3;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc3() {
        int countJob=4;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc4() {
        int countJob=5;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc5() {
        int countJob=6;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc6() {
        int countJob=7;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc7() {
        int countJob=8;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc8() {
        int countJob=9;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
    @Scheduled(initialDelay = 5000L,fixedDelay=3596400000L)
    public void jobFunc9() {
        int countJob=10;
        if(isClientJob) {
            logger.info("启动 第{}个线程作业", countJob);
            innerJobThreadWorker(countJob);
        }
    }
}

